/*!
	@file
	@author		Albert Semenov
	@date		05/2009
*/


#include "Precompiled.h"
#include "MemDataStream.h"

namespace stream
{

	MemDataStream::MemDataStream(void* data, size_t dataLen) :
		mData((MyGUI::uint8*)data),
		mDataLen(dataLen),
		mFile(NULL),
		mCurPos(0)
	{
	}

	MemDataStream::MemDataStream(easy2d::File* pFile) :
		mData((MyGUI::uint8*)pFile->getBufferPtr()),
		mDataLen(pFile->getLength()),
		mFile(pFile),
		mCurPos(0)
	{
	}

	MemDataStream::~MemDataStream()
	{
		if (mFile != NULL) {
			SAFE_DELETE(mFile);
		}
	}

	bool MemDataStream::eof()
	{
		if (mCurPos >= mDataLen-1)
			return true;

		return false;
	}

	size_t MemDataStream::size()
	{
		return mDataLen;
	}

	void MemDataStream::readline(std::string& _source, MyGUI::Char _delim)
	{
		MyGUI::uint8* ptrBegin = getCurDataPtr();
		size_t leftSize = getLeftSize();
		size_t pos = 0;
		for (size_t i=0; i<leftSize; i++) {
			if (*(ptrBegin+i) == _delim) {
				pos;
				break;
			}
			pos++;
		}
		
		_source = (const char*)ptrBegin;
		_source.resize(pos-1);
		addOffset(pos+1);
	}

	size_t MemDataStream::read(void* _buf, size_t _count)
	{
		size_t realCount = _count;
		if (_count > getLeftSize())
			realCount = getLeftSize();
		
		memcpy(_buf, getCurDataPtr(), realCount);
		addOffset(realCount);

		return realCount;
	}

	size_t MemDataStream::addOffset(size_t size)
	{
		size_t realSize = size;
		if (size > getLeftSize())
			realSize = getLeftSize();

		
		mCurPos += realSize;

		return realSize;
	}

	size_t MemDataStream::getLeftSize()
	{
		return mDataLen - mCurPos;
	}

	MyGUI::uint8* MemDataStream::getCurDataPtr()
	{
		return mData + mCurPos;
	}

} // namespace base
